package com.notary.tx_live_plugin.platform;

import android.content.Context;
import android.view.View;

import com.notary.tx_live_plugin.util.TxConstant;
import com.notary.tx_live_plugin.util.PlayManager;
import com.notary.tx_live_plugin.widget.TxLivePlayView;

import java.util.HashMap;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;

/**
 * 直播录像视频的在线播放的platform view，原生提供给flutter的widget控件
 */
public class TxLivePlayPlatformView implements PlatformView{

    private TxLivePlayView txLivePlayView;
    private final Context context;
    private MethodChannel channel;
    private final PlayManager playManager;

    public TxLivePlayPlatformView(BinaryMessenger binaryMessenger, Context context, int viewId, HashMap<String, Object> params) {
        this.context = context;
        final String channelName = TxConstant.Channel.PLAY_PREFIX + viewId;
        playManager = PlayManager.getInstance();
        channel = new MethodChannel(binaryMessenger, channelName);
        channel.setMethodCallHandler(new PlayMethodCallHandlerImpl(playManager));
        playManager.setOnPlayCallback((methodName, data) -> {
            if(channel != null) channel.invokeMethod(methodName,data);
        });
    }

    @Override
    public View getView() {
        if(txLivePlayView == null) {
            txLivePlayView = new TxLivePlayView(context);
            playManager.setTxLivePlayView(txLivePlayView);
        }
        return txLivePlayView;
    }

    @Override
    public void dispose() {
        if(txLivePlayView != null) txLivePlayView.onDestroy();
        txLivePlayView = null;
        playManager.clear();
        if(channel != null) channel.setMethodCallHandler(null);
        channel = null;
    }
}
